# face detector 4.2
# CNN-based face detector
# 卷积神经网络

import cv2
import dlib
from matplotlib import pyplot as plt


# visualize functions
def show_img_with_matplotlib(color_img, title, pos):
    img_rgb = color_img[:, :, ::-1]
    ax = plt.subplot(1, 1, pos)
    plt.imshow(img_rgb)
    plt.title(title, fontsize=8)
    plt.axis('off')


# load image
img = cv2.imread("picture/005.jpg")

# create a face detector
cnn_face_detector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat")

# perform detection
rects = cnn_face_detector(img, 0)
print(rects)


# 检测器返回 mmod_rectangles 对象，它是一个 mmod_rectangle 对象的列表，
# 并且 mmod_rectangle 对象有两个成员变量—— dlib.rectangle 对象和预测的置信度分数
# draw face detection box
def show_detection(image, faces):
    for face in faces:
        cv2.rectangle(image, (face.rect.left(), face.rect.top()), (face.rect.right(), face.rect.bottom()), (255, 0, 0),5)
    return image


# draw face detection box
img_faces = show_detection(img.copy(), rects)

# visualize
show_img_with_matplotlib(img_faces, "cnn_face_detector(img,0):" + str(len(rects)), 1)

plt.show()
